class User < ApplicationRecord
  # upload file
  mount_uploaders :avatars, AvatarUploader
  serialize :avatars, JSON

  attr_accessor :remember_token

  before_save {self.email = email.downcase}

  # 如果用户被删除的话，文章和评论都要被删除
  has_many :articles, dependent: :destroy
  has_many :comments, dependent: :destroy

  validates :name, presence: true, length: {maximum: 50}
  validates :email, presence: true, length: {maximum: 255},
            uniqueness: {case_sensitive: false}

  # 添加密码
  has_secure_password
  validates :password, presence: true,
             length: {minimum: 6}, allow_nil: true

  # #　返回指定字符串的哈希摘要
  # def self.digest(string)
  #   cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
  #                                                 BCrypt::Engine.cost
  #
  #   BCrypt::Password::create(string, cost: cost)
  # end
  #
  # def self.new_token
  #   SecureRandom.urlsafe_base64
  # end

  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  class << self
    # 返回指定字符串的哈希摘要
    def digest(string)
      cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                 BCrypt::Engine.cost

      BCrypt::Password::create(string, cost: cost)
    end

    # 返回一个随机令牌
    def new_token
      SecureRandom.urlsafe_base64
    end
  end

  # 如果指定的令牌和摘要匹配，返回 true
  def authenticated?(remember_token)
    return false if remember_digest.nil?
    BCrypt::Password::new(remember_digest).is_password?(remember_token)
  end

  # 忘记用户(持久会话)
  def forget
    update_attribute(:remember_digest, nil)
  end
end
